package com.sgcc.dlsc.redis.demo.service.impl;

import com.sgcc.comm.util.ResultUtil;
import com.sgcc.dlsc.redis.demo.service.RedisServerService;
import org.jboss.logging.Logger;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


/**
 * @Author: 李孟帅
 * @CreateTime: 2019-10-31 09:04
 * @Description: ${Description}
 */
@Service
public class RedisServerServiceImpl implements RedisServerService {
    private static final Logger LOGGER = Logger.getLogger(RedisServerServiceImpl.class);

    @Resource
    private RedisClusterConnection  redisClusterConnection;

    @Override
    public ResultUtil addKey(String key, String value) {
        byte[] bytes = redisClusterConnection.get(key.getBytes());
        if (bytes != null) {
            return ResultUtil.result("添加的key已存在，添加失败，其值为：" + new String(bytes));
        }
        Boolean set = redisClusterConnection.set(key.getBytes(), value.getBytes());
        if (set != null && set) {
            return ResultUtil.result("添加成功");
        }
        return ResultUtil.result("添加失败");
    }

    @Override
    public ResultUtil queryKey( String key) {

        byte[] value = redisClusterConnection.get(key.getBytes());
        if (value != null) {
            return ResultUtil.success(new String(value));
        }
        return ResultUtil.result("查询的key不存在");
    }

    @Override
    public ResultUtil deleteKey( String key) {
        Long del = redisClusterConnection.del(key.getBytes());
        if (del != null && del == 1) {
            return ResultUtil.result("删除成功");
        }
        return ResultUtil.result("删除失败,key不存在");
    }

    @Override
    public ResultUtil updateKey(String key, String value) {
        byte[] oldValue = redisClusterConnection.getSet(key.getBytes(), value.getBytes());
        if (oldValue != null) {
            return ResultUtil.result("修改成功:原来值为" + new String(oldValue));
        }
        return ResultUtil.result("添加成功");
    }

    @Override
    public ResultUtil queryAll() {
        Set<byte[]> keys = redisClusterConnection.keys("*".getBytes());
        Set<String> AllKeys=new HashSet<>();
        if (keys!=null){
            for (byte[] key : keys) {
                AllKeys.add(new String(key));
            }
            LOGGER.info("查询成功");
            return ResultUtil.success(AllKeys);
        }
        return ResultUtil.result("没有key");
    }


}
